<template>
    <!-- 巡检管理 / 区域列表 -->
    <div class="layout-padding">
      <basic-container class="layout-padding-auto layout-padding-view">
        <avue-crud
            v-model='form'
            ref='crud'
            :page='page'
            :data='data'
            :permission='permissionList'
            :table-loading='tableLoading'
            :option='tableOption'
            :before-open='handleOpenBefore'
            :span-method='spanMethod'
            @on-load='getList'
            @search-change='searchChange'
            @refresh-change='refreshChange'
            @size-change='sizeChange'
            @current-change='currentChange'
            @row-update='handleUpdate'
            @row-save='handleSave'
            @row-del='rowDel'
            @selection-change='selectionChange'
        >
          <template #menu-left>
            <el-button
                class='filter-item'
                plain
                type='primary'
                icon='el-icon-delete'
                @click='plDelete'
            >
              批量删除
            </el-button>
          </template>
          <template #menu='{ row, size, type,index }'>
            <el-button
                text
                type='primary'
                icon='el-icon-edit'
                :size='size'
                @click='handleUpdateBtn(row,index)'>编辑
            </el-button>
            <!--          <el-button-->
            <!--            v-show='row.$index === 0 || row.$index'-->
            <!--            link-->
            <!--            :size='size'-->
            <!--            :type='type'-->
            <!--            icon="el-icon-plus"-->
            <!--            @click='handleAdd(row, size, type)'-->
            <!--          >添加-->
            <!--          </el-button>-->
            <el-button @click='openDialog(row)' link :size='size' icon='el-icon-connection'
                       :type='type'>关联设备
            </el-button>
          </template>
          <template #subareaJzbm-form='scope'>
            <avue-select
                v-model='form.subareaJzbm'
                placeholder='请选择建筑'
                filterable
                :dic='buildingsOptions'
                :props='buildingsProps'
                :disabled='scope.column.boxType === "edit"'
                @change='placenoChange'
            ></avue-select>
          </template>
          <template #subareaLc-form='scope'>
            <avue-select
                v-model='form.subareaLc'
                placeholder='请选择楼层'
                filterable
                :dic='floorsOptions'
                :disabled='scope.column.boxType === "edit"'
                :props='floorsProps'
                @change='placenoChangeFloor($event,scope)'
            ></avue-select>
          </template>
          <template #subareaCn-form='scope'>
            <avue-select
                v-model='form.subareaCn'
                placeholder='请选择分区名称'
                filterable
                :disabled='scope.column.boxType === "edit"'
                :dic='namesOptions'
                :props='namesProps'
                @change='placenoChangeName($event,scope)'
            ></avue-select>
          </template>
          <template #inspectionName-form>
            <avue-select
                v-model='form.inspectionName'
                placeholder='请选择区域名称'
                filterable
                :dic='regionsOptions'
                :props='regionsProps'
                @change='placenoChangeRegions'
            ></avue-select>
          </template>
          <template #inspectionClassification-form>
            <avue-select
                v-model='form.inspectionClassification'
                placeholder='请选择区域分类'
                filterable
                :dic='classifyOptions'
                :props='classifyProps'
                @change='classifyChange'
            ></avue-select>
          </template>
        </avue-crud>
      </basic-container>
      <equipmentVue
          :id='id'
          :DeviceData='DeviceData'
          ref='equipmentVue'
          @addEquipment='addEquipment'
          @closeDialog='closeDialog'
          v-if='dialogFormVisible'
      />
    </div>
  </template>
  
  <script>
  import {tableOption} from '/@/const/crud/check/omichecklist'
  import {
    getAllBuildings,
    getAllFloor,
    getBamSubareaCode,
    getlistData,
    addObj,
    delObj,
    putObj,
    delAllObj,
    getNameList,
    getOminspectionList
  } from '/@/api/check/omichecklist'
  import equipmentVue from './equipment.vue'
  import {mapGetters} from 'vuex'
  import {ElLoading} from "element-plus";
  
  export default {
    name: 'omichecklist',
    components: {equipmentVue},
    data() {
      let _this = this
      return {
        dialogFormVisible: false,
        parentId: 0,
        id: '',
        DeviceData: '',
        form: {},
        buildingsOptions: [],
        buildingsProps: {
          label: 'buildingsCn',
          value: 'buildingsId'
        },
        floorsOptions: [],
        floorsProps: {
          label: 'floorCn',
          value: 'floorCode'
        },
        namesOptions: [],
        namesProps: {
          label: 'subareaCn',
          value: 'subareaCode'
        },
        regionsOptions: [],
        regionsProps: {
          label: 'subareaCn',
          value: 'subareaCn'
        },
        searchForm: {},
        data: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,
        spanArr: [
          {
            prop: 'inspectionClassificationName',
            span: []
          }
        ],
        classifyOptions: [],
        classifyProps: {
          label: 'name',
          value: 'id'
        },
        selectList: [],
        editData: {},
        loading: null
      }
    },
    computed: {
    //   ...mapGetters(['permissions']),
      permissionList() {
        return {
        //   getBtn: this.validData(this.permissions.om_ominspectionList_get, false),
        //   addBtn: this.validData(this.permissions.om_ominspectionList_add, false),
        //   editBtn: this.validData(this.permissions.om_ominspectionList_edit, false),
        //   delBtn: this.validData(this.permissions.om_ominspectionList_del, false)
        }
      }
    },
    mounted() {
    },
    methods: {
      classifyChange(val) {
        let obj = this.classifyOptions.find((item) => {
          return item.id === val.value
        })
        this.form.inspectionClassificationName = obj?.name
      },
      openLoading() {
        this.loading = ElLoading.service({
          lock: true,
          text: 'Loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
      },
      closeLoading() {
        this.loading.close()
      },
      closeDialog() {
        this.dialogFormVisible = false
      },
      handleUpdateBtn(row, index) {
        this.$refs.crud.rowEdit(row, index)
        this.form.subareaJzbm = row.buildingsId
        this.form.subareaLc = row.floorCode
        this.form.inspectionClassification = parseInt(row.inspectionClassification)
        this.editData.subareaCn = row.subareaCode
        this.editData.inspectionName = row.inspectionName
      },
      // 关联时刷新页面
      addEquipment() {
        this.getList(this.page)
      },
      placenoChange(data) {
        // getAllFloor({floorPid: data.value}).then((res) => {
        getAllFloor({current:1,size:9999}).then((res) => {
          this.floorsOptions = res.data.records;
        })
  
      },
      // 选择楼层触发
      placenoChangeFloor(data, scope) {
        if (data.value) {
          // 获取分区名称列表数据
          getNameList({current: 1, size: 9999}).then((res) => {
            this.form.subareaCn = ''
            this.namesOptions = res.data.records
            if (scope.column.boxType === 'edit') {
              this.form.subareaCn = this.editData.subareaCn
            }
          })
        }
  
      },
      // 选择分区名称
      placenoChangeName(val, scope) {
        const obj = this.namesOptions.find((item) => {
          return item.subareaCode === val.value
        })
        this.form.inspectionName = ''
        this.regionsOptions = []
        if (obj?.childrens.length === 0) {
          return this.$message.warning('该分区下不包含任何房间区域，请在空间分区中创建！')
        }
        this.regionsOptions = obj?.childrens
        this.form.subareaEn = obj?.subareaEn
        if (scope.column.boxType === 'edit') {
          this.form.inspectionName = this.editData.inspectionName
        }
      },
      // 选择区域名称
      placenoChangeRegions(val) {
        let obj = this.regionsOptions?.find((item) => {
          return item.subareaCn === val.value
        })
        this.form.inspectionCode = obj?.subareaCode
        this.form.inspectionSize = obj?.subareaCoords
      },
      // 打开关联设备弹出框
      openDialog(row) {
        this.id = row.id
        if (row.associatedDevice != '') {
          this.DeviceData = row.associatedDeviceFlag
        } else {
          this.DeviceData = []
        }
        this.dialogFormVisible = true
      },
      // 添加
      handleAdd(row, size, type) {
        this.parentId = row.id
        this.$refs.crud.rowAdd()
      },
      // 全选按钮
      selectionChange(list) {
        this.selectList = list
      },
      // 获取表格数据
      getList(page, params) {
        this.data = []
        this.tableLoading = true
        getlistData(
            Object.assign(
                {
                  current: page.currentPage,
                  size: page.pageSize
                },
                params,
                this.searchForm
            )
        )
            .then((response) => {
              this.data = response.data.records
              this.page.total = response.data.total
              this.tableLoading = false
              this.rowSort()
              this.rowCalc()
            })
            .catch(() => {
              this.tableLoading = false
            })
      },
      // 删除
      rowDel(row, index) {
        this.$confirm('是否确认删除' + row.inspectionName, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
            .then(function () {
              return delObj(row.id)
            })
            .then((data) => {
              this.$message.success('删除成功')
              this.getList(this.page)
            })
            .catch((cancelorerror) => {
            })
      },
      // 修改更新数据
      handleUpdate(row, index, done, loading) {
        row.inspectionClassification = row.inspectionClassification + ''
        putObj(row)
            .then((data) => {
              this.$message.success('修改成功')
              done()
              this.getList(this.page)
            })
            .catch(() => {
              loading()
            })
      },
      // 新增数据
      handleSave: function (row, done, loading) {
        row.parentId = this.parentId
        row.inspectionCode = this.form.inspectionCode
        row.buildingsId = this.form.subareaJzbm
        row.floorCode = this.form.subareaLc
        row.subareaCode = this.form.subareaCn
        row.inspectionClassification = row.inspectionClassification + ''
        addObj(row)
            .then((data) => {
              this.$message.success('添加成功')
              done()
              this.parentId = 0
              this.getList(this.page)
            })
            .catch(() => {
              loading()
            })
      },
      // 分页大小
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      // 改变页数
      currentChange(current) {
        this.page.currentPage = current
      },
      // 点击搜索
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      // 刷新表格
      refreshChange() {
        this.getList(this.page)
      },
      // 打开前回调
      handleOpenBefore(show, type) {
        getOminspectionList({current: 1, size: 999}).then((res) => {
          this.classifyOptions = res.data.records
        })
        getAllBuildings({current:1,size:9999}).then((res) => {
          this.buildingsOptions = res.data.records
        })
        getAllFloor({current:1,size:9999}).then((res) => {
          this.floorsOptions = res.data.records;
        })
        show()
      },
      //批量删除
      plDelete() {
        if (this.selectList.length > 0) {
          this.$confirm('是否确认删除以选择的数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
              .then(() => {
                let ids = []
                this.selectList.forEach((data) => {
                  ids.push(data.id+'')
                })
                this.openLoading()
                return delAllObj(ids).then((res) => {
                  this.closeLoading()
                  this.$message.success('删除成功')
                  this.getList(this.page)
                }).catch(()=>{
                  this.closeLoading()
                  this.$message.error('删除失败')
                })
              })
              .then((data) => {
              })
              .catch((cancelorerror) => {
              })
        }
      },
      // 合并列行
      rowCalc() {
        this.spanArr.forEach((ele, index) => {
          let parent
          if (index !== 0) parent = this.spanArr[ele.parent || index - 1].span
          ele.span = this.rowSpan(ele.prop, parent)
        })
      },
      rowSort(list) {
        let propList = this.spanArr.map(ele => ele.prop)
        this.spanArr.forEach((ele, index) => {
          let key = ele.prop
          this.data = this.data.sort((a, b) => {
            let flag = true
            for (let i = 0; i < index; i++) {
              let prop = this.spanArr[i].prop
              flag = flag && a[prop] == b[prop]
            }
            if (flag) {
              if (a[key] < b[key]) {
                return 1
              } else if (a[key] > b[key]) {
                return -1
              }
              return 0
            }
            return 0
          })
        })
      },
      rowSpan(key, parent) {
        let list = []
        let position = 0
        this.data.forEach((item, index) => {
          if (index === 0) {
            list.push(1)
            let position = 0
          } else {
            if (this.data[index][key] === this.data[index - 1][key]) {
              if (parent && parent[index] !== 0) {
                list.push(1)
                position = index
              } else {
                list[position] += 1
                list.push(0)
              }
            } else {
              list.push(1)
              position = index
            }
          }
        })
        return list
      },
      spanMethod({row, column, rowIndex, columnIndex}) {
        for (let i = 0; i < this.spanArr.length; i++) {
          const ele = this.spanArr[i]
          if (column.property == ele.prop) {
            const _row = ele.span[rowIndex]
            const _col = _row > 0 ? 1 : 0
            return {
              rowspan: _row,
              colspan: _col
            }
          }
        }
      }
    }
  }
  </script>
  <style lang='scss'>
  .region-code {
    & > div:nth-child(1) {
      width: 70%;
    }
  
    & > div:nth-child(2) {
      width: 30%;
    }
  }
  </style>
  